import React from 'react'
import { Route } from 'react-router'
// 导入子组件
import Index from '../Index'
import LookingRoom from '../LookingRoom'
import Consulting from '../Consulting'
import My from '../My'
// 导入 TabBar
import { TabBar } from 'antd-mobile'
import './index.scss'

const tabbarItems = [
  {
    title: '首页',
    icon: 'iconfont icon-index-copy',
    path: '/home',
  },
  {
    title: '找房',
    icon: 'iconfont icon-chazhaofangyuan',
    path: '/home/lookingRoom',
  },
  {
    title: '资讯',
    icon: 'iconfont icon-shouye',
    path: '/home/consulting',
  },
  {
    title: '我的',
    icon: 'iconfont icon-wode',
    path: '/home/my',
  },
]
export default class Home extends React.Component {
  state = {
    // 默认选择的tabbar菜单项
    selectedTab: this.props.location.pathname,
  }

  // 组件更新调用----解決导航菜单跳转到TabBar不高亮问题
  componentDidUpdate(prevProps) {
    // prevProps 上一次的props，此处也就是上一次的路由信息
    // this.props 当前最新的props，此处也就是最新的路由信息
    // 注意：在该钩子函数中更新状态时，一定要在 条件判断 中进行，否则会造成递归更新的问题
    if (prevProps.location.pathname !== this.props.location.pathname) {
      this.setState({
        selectedTab: this.props.location.pathname,
      })
    }
  }

  // 渲染 TabBar.Item
  renderTabBarItem() {
    return tabbarItems.map((item) => (
      <TabBar.Item
        title={item.title}
        key={item.title}
        icon={<i className={item.icon}></i>}
        selectedIcon={<i className={item.icon}></i>}
        selected={this.state.selectedTab === item.path}
        onPress={() => {
          this.setState({
            selectedTab: item.path,
          })
          // 路由切换
          this.props.history.push(item.path)
        }}
        data-seed="logId"
      ></TabBar.Item>
    ))
  }

  render() {
    return (
      <div className="home">
        {/* 渲染子组件 默认为模糊匹配，加exact为精确匹配 */}
        <Route path="/home" exact component={Index} />
        <Route path="/home/lookingRoom" component={LookingRoom} />
        <Route path="/home/consulting" component={Consulting} />
        <Route path="/home/my" component={My} />
        {/* TabBar */}
        <TabBar
          unselectedTintColor="#888"
          tintColor="#21b97a"
          barTintColor="white"
          noRenderContent={true}
        >
          {this.renderTabBarItem()}
        </TabBar>
      </div>
    )
  }
}
